﻿using UnityEngine;
using System.Collections;
namespace UnityEngine.DesignPattern
{
    public class SingletonBehaviour<T>
#if WRB_HIGHSTAKES
        : BaseScreen where T : MonoBehaviour
#else
        : MonoBehaviour where T : MonoBehaviour 
#endif
    {
        static T _sharedInstance;
        static GameObject _sharedGameObject;
        static string sharedGameObjectName = typeof(T).Name;

        protected static GameObject sharedGameObject
        {
            get
            {
                if (_sharedGameObject == null)
                    _sharedGameObject = GetSharedGameObject();
                return _sharedGameObject;
            }
        }

        protected static T sharedInstance
        {
            get
            {
                if (_sharedInstance == null)
                    _sharedInstance = GetSharedInstance();
                return _sharedInstance;
            }
        }

        static GameObject GetSharedGameObject()
        {
            GameObject result = GameObject.Find(sharedGameObjectName);
            if (result)
                GameObject.DontDestroyOnLoad(result);
            else
                result = CreateSharedGameObject();
            return result;
        }

        static GameObject CreateSharedGameObject()
        {
            GameObject result = new GameObject(sharedGameObjectName);
            if (result)

            {

                //result.hideFlags = HideFlags.HideInHierarchy;
                GameObject.DontDestroyOnLoad(result);
            }
            else
                Debug.LogError("Failed to Create Singleton GameObject");
            return result;
        }

        static T GetSharedInstance()
        {
            T result = sharedGameObject.GetComponent<T>();
            if (!result)
                result = CreateSharedInstance();
            return result;
        }

        static T CreateSharedInstance()
        {
            T result = sharedGameObject.AddComponent<T>();
            if (!result)
                Debug.LogError("Failed to Attach SingletonBehaviour");
            return result;
        }
    }
}